import 'dart:async';
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart'; // 启用权限管理插件
import 'notification_service.dart'; // 🔥 导入通知服务，用于测试HEAD_UP通知

/// 权限服务类
/// 
/// 权限管理功能（暂时注释高德定位插件）
class PermissionService extends GetxService {
  // 高德定位插件实例（暂时注释）
  // final AMapFlutterLocation _locationPlugin = AMapFlutterLocation(); // 暂时注释，解决构建问题
  
  // 位置权限状态
  final RxBool _locationPermissionGranted = false.obs;
  // 麦克风权限状态
  final RxBool _microphonePermissionGranted = false.obs;
  // 通知权限状态
  final RxBool _notificationPermissionGranted = false.obs;
  // 系统弹出窗口权限状态（用于HEAD_UP通知）
  final RxBool _systemAlertPermissionGranted = false.obs;
  
  // 防止重复请求权限的标志
  bool _isRequestingMicPermission = false;
  bool _isRequestingLocationPermission = false;
  bool _isRequestingNotificationPermission = false;
  bool _isRequestingSystemAlertPermission = false;

  // 获取位置权限状态
  bool get isLocationPermissionGranted => _locationPermissionGranted.value;
  // 获取麦克风权限状态
  bool get isMicrophonePermissionGranted => _microphonePermissionGranted.value;
  // 获取通知权限状态
  bool get isNotificationPermissionGranted => _notificationPermissionGranted.value;
  // 获取系统弹出窗口权限状态
  bool get isSystemAlertPermissionGranted => _systemAlertPermissionGranted.value;

  // 初始化
  @override
  void onInit() {
    super.onInit();
    developer.log('PermissionService onInit');
  }

  // 🔑 请求位置权限（使用真实的权限请求）
  Future<bool> requestLocationPermission() async {
    developer.log('🔐 =============== 开始请求位置权限 ===============');
    
    // 如果已经在请求权限，直接返回当前状态
    if (_isRequestingLocationPermission) {
      developer.log('⚠️ 正在请求权限中，跳过重复请求');
      return _locationPermissionGranted.value;
    }
    
    _isRequestingLocationPermission = true;
    try {
      developer.log('🔍 检查当前位置权限状态...');
      
      // 检查定位权限状态
      final permission = Permission.location;
      PermissionStatus status = await permission.status;
      
      developer.log('📋 当前权限状态: $status');
      
      if (status == PermissionStatus.granted) {
        developer.log('✅ 位置权限已授予');
        _locationPermissionGranted.value = true;
        return true;
      }
      
      // 如果权限被永久拒绝，引导用户到设置页面
      if (status == PermissionStatus.permanentlyDenied) {
        developer.log('🚫 权限被永久拒绝，用户需要手动在设置中开启');
        _locationPermissionGranted.value = false;
        return false;
      }
      
      // 请求权限
      developer.log('📲 正在请求位置权限...');
      status = await permission.request();
      developer.log('📋 权限请求结果: $status');
      
      if (status == PermissionStatus.granted) {
        developer.log('✅ 位置权限请求成功');
        _locationPermissionGranted.value = true;
        return true;
      } else {
        developer.log('❌ 位置权限请求失败: $status');
        _locationPermissionGranted.value = false;
        return false;
      }
      
    } catch (e) {
      developer.log('💥 请求位置权限异常: $e');
      _locationPermissionGranted.value = false;
      return false;
    } finally {
      _isRequestingLocationPermission = false;
      developer.log('🏁 =============== 位置权限请求结束 ===============');
    }
  }

  // 🎤 请求麦克风权限（使用真实的权限请求）
  Future<bool> requestMicrophonePermission() async {
    developer.log('🔐 =============== 开始请求麦克风权限 ===============');
    
    // 如果已经在请求权限，直接返回当前状态
    if (_isRequestingMicPermission) {
      developer.log('⚠️ 正在请求麦克风权限中，跳过重复请求');
      return _microphonePermissionGranted.value;
    }
    
    _isRequestingMicPermission = true;
    try {
      developer.log('🔍 检查当前麦克风权限状态...');
      
      // 检查麦克风权限状态
      final permission = Permission.microphone;
      PermissionStatus status = await permission.status;
      
      developer.log('📋 当前麦克风权限状态: $status');
      
      if (status == PermissionStatus.granted) {
        developer.log('✅ 麦克风权限已授予');
        _microphonePermissionGranted.value = true;
        return true;
      }
      
      // 如果权限被永久拒绝，引导用户到设置页面
      if (status == PermissionStatus.permanentlyDenied) {
        developer.log('🚫 麦克风权限被永久拒绝，用户需要手动在设置中开启');
        _microphonePermissionGranted.value = false;
        return false;
      }
      
      // 请求麦克风权限
      developer.log('📲 正在请求麦克风权限...');
      status = await permission.request();
      developer.log('📋 麦克风权限请求结果: $status');
      
      if (status == PermissionStatus.granted) {
        developer.log('✅ 麦克风权限请求成功');
        _microphonePermissionGranted.value = true;
        return true;
      } else {
        developer.log('❌ 麦克风权限请求失败: $status');
        _microphonePermissionGranted.value = false;
        return false;
      }
      
    } catch (e) {
      developer.log('💥 请求麦克风权限异常: $e');
      _microphonePermissionGranted.value = false;
      return false;
    } finally {
      _isRequestingMicPermission = false;
      developer.log('🏁 =============== 麦克风权限请求结束 ===============');
    }
  }

  // 🗺️ 显示位置权限说明对话框
  Future<bool> _showLocationPermissionDialog() async {
    final completer = Completer<bool>();
    bool isCompleted = false;
    
    await Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(13),
        ),
        child: Container(
          width: double.infinity,
          padding: const EdgeInsets.fromLTRB(20, 20, 20, 8),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 权限图标和标题
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.location_on, size: 22, color: Colors.blue[700]),
                  const SizedBox(width: 10),
                  const Text(
                    '位置权限',
                    style: TextStyle(
                      fontSize: 18, 
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20),
              // 权限说明
              Text(
                '玩真的需要获取您的位置信息，以便为您提供：\n\n• 附近的商店和评论\n• 精准的定位服务\n• 更好的本地化体验',
                style: TextStyle(fontSize: 14, color: Colors.grey[800]),
                textAlign: TextAlign.left,
              ),
              const SizedBox(height: 24),
              const Divider(height: 1, thickness: 0.5),
              // 按钮区域
              IntrinsicHeight(
                child: Row(
                  children: [
                    Expanded(
                      child: TextButton(
                        onPressed: () {
                          Get.back();
                          if (!isCompleted) {
                            isCompleted = true;
                            completer.complete(false);
                          }
                        },
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.grey[600],
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        child: const Text(
                          '不允许', 
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                    ),
                    const VerticalDivider(width: 1, thickness: 0.5),
                    Expanded(
                      child: TextButton(
                        onPressed: () {
                          Get.back();
                          if (!isCompleted) {
                            isCompleted = true;
                            completer.complete(true);
                          }
                        },
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.blue[700],
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        child: const Text(
                          '允许', 
                          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: false,
    );
    
    if (!isCompleted) {
      isCompleted = true;
      completer.complete(false);
    }
    
    return completer.future;
  }

  // 显示系统风格的权限请求对话框
  Future<bool> _showSystemStylePermissionDialog(String title, String message, {IconData icon = Icons.mic}) async {
    final completer = Completer<bool>();
    bool isCompleted = false;
    
    // 显示类似原生系统的权限对话框
    await Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(13),
        ),
        child: Container(
          width: double.infinity,
          padding: const EdgeInsets.fromLTRB(20, 20, 20, 8),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(icon, size: 22, color: Colors.grey[700]),
                  const SizedBox(width: 10),
                  Text(
                    title,
                    style: const TextStyle(
                      fontSize: 18, 
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20),
              Text(
                message,
                style: TextStyle(fontSize: 14, color: Colors.grey[800]),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
              const Divider(height: 1, thickness: 0.5),
              IntrinsicHeight(
                child: Row(
                  children: [
                    Expanded(
                      child: TextButton(
                        onPressed: () {
                          Get.back();
                          if (!isCompleted) {
                            isCompleted = true;
                            completer.complete(false);
                          }
                        },
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.deepPurple,
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        child: const Text(
                          '拒绝', 
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                    ),
                    const VerticalDivider(width: 1, thickness: 0.5),
                    Expanded(
                      child: TextButton(
                        onPressed: () {
                          Get.back();
                          if (!isCompleted) {
                            isCompleted = true;
                            completer.complete(true);
                          }
                        },
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.deepPurple,
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        child: const Text(
                          '允许', 
                          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: false,
    );
    
    // 如果对话框关闭但completer尚未完成，则完成为false
    if (!isCompleted) {
      isCompleted = true;
      completer.complete(false);
    }
    
    return completer.future;
  }



  // 显示权限被永久拒绝对话框
  Future<bool> _showPermissionDeniedDialog() async {
    final completer = Completer<bool>();
    bool isCompleted = false;
    
    await Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(13),
        ),
        child: Container(
          width: double.infinity,
          padding: const EdgeInsets.fromLTRB(20, 20, 20, 8),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.settings, size: 22, color: Colors.red[700]),
                  const SizedBox(width: 10),
                  const Text(
                    '需要手动开启权限',
                    style: TextStyle(
                      fontSize: 18, 
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20),
              Text(
                '位置权限已被永久拒绝，请前往设置页面手动开启位置权限',
                style: TextStyle(fontSize: 14, color: Colors.grey[800]),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
              const Divider(height: 1, thickness: 0.5),
              IntrinsicHeight(
                child: Row(
                  children: [
                    Expanded(
                      child: TextButton(
                        onPressed: () {
                          Get.back();
                          if (!isCompleted) {
                            isCompleted = true;
                            completer.complete(false);
                          }
                        },
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.grey[600],
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        child: const Text(
                          '取消', 
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                    ),
                    const VerticalDivider(width: 1, thickness: 0.5),
                    Expanded(
                      child: TextButton(
                        onPressed: () {
                          Get.back();
                          if (!isCompleted) {
                            isCompleted = true;
                            completer.complete(true);
                          }
                        },
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.deepPurple,
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        child: const Text(
                          '去设置', 
                          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: false,
    );
    
    if (!isCompleted) {
      isCompleted = true;
      completer.complete(false);
    }
    
    return completer.future;
  }

  // 🔔 请求通知权限（系统级，强制检查并申请）
  Future<bool> requestNotificationPermission({bool forceRequest = false}) async {
    developer.log('🔐 =============== 开始请求通知权限 ===============');
    
    // 如果已经在请求权限，直接返回当前状态
    if (_isRequestingNotificationPermission) {
      developer.log('⚠️ 正在请求通知权限中，跳过重复请求');
      return _notificationPermissionGranted.value;
    }
    
    _isRequestingNotificationPermission = true;
    try {
      developer.log('🔍 详细检查当前通知权限状态...');
      
      // 检查通知权限状态
      final permission = Permission.notification;
      PermissionStatus status = await permission.status;
      
      developer.log('📋 当前通知权限状态: $status');
      developer.log('📋 权限状态详细信息:');
      developer.log('  - isGranted: ${status.isGranted}');
      developer.log('  - isDenied: ${status.isDenied}');
      developer.log('  - isPermanentlyDenied: ${status.isPermanentlyDenied}');
      developer.log('  - isRestricted: ${status.isRestricted}');
      developer.log('  - isLimited: ${status.isLimited}');
      
      // 如果权限已授予且不强制重新申请
      if (status == PermissionStatus.granted && !forceRequest) {
        developer.log('✅ 通知权限已授予，无需重新申请');
        _notificationPermissionGranted.value = true;
        return true;
      }
      
      // 如果权限未授予或强制重新申请
      if (status != PermissionStatus.granted || forceRequest) {
        developer.log('📲 正在请求通知权限（系统级）...');
        developer.log('📲 申请原因: ${forceRequest ? "强制重新申请" : "权限未授予($status)"}');
        
        status = await permission.request();
        developer.log('📋 通知权限申请结果: $status');
        
        if (status == PermissionStatus.granted) {
          developer.log('✅ 通知权限申请成功');
          _notificationPermissionGranted.value = true;
          return true;
        } else if (status == PermissionStatus.permanentlyDenied) {
          developer.log('🚫 通知权限被永久拒绝，需要用户手动在设置中开启');
          _notificationPermissionGranted.value = false;
          return false;
        } else {
          developer.log('❌ 通知权限申请失败: $status');
          _notificationPermissionGranted.value = false;
          return false;
        }
      }
      
      return false;
      
    } catch (e) {
      developer.log('💥 请求通知权限异常: $e');
      _notificationPermissionGranted.value = false;
      return false;
    } finally {
      _isRequestingNotificationPermission = false;
      developer.log('🏁 =============== 通知权限请求结束 ===============');
    }
  }

  // 📱 请求系统弹出窗口权限（系统级，无自定义dialog）
  Future<bool> requestSystemAlertPermission() async {
    developer.log('🔐 =============== 开始请求系统弹出窗口权限 ===============');
    
    // 如果已经在请求权限，直接返回当前状态
    if (_isRequestingSystemAlertPermission) {
      developer.log('⚠️ 正在请求系统弹出窗口权限中，跳过重复请求');
      return _systemAlertPermissionGranted.value;
    }
    
    _isRequestingSystemAlertPermission = true;
    try {
      developer.log('🔍 检查当前系统弹出窗口权限状态...');
      
      // 检查系统弹出窗口权限状态
      final permission = Permission.systemAlertWindow;
      PermissionStatus status = await permission.status;
      
      developer.log('📋 当前系统弹出窗口权限状态: $status');
      
      if (status == PermissionStatus.granted) {
        developer.log('✅ 系统弹出窗口权限已授予');
        _systemAlertPermissionGranted.value = true;
        return true;
      }
      
      // 直接请求系统弹出窗口权限（系统级申请）
      developer.log('📲 正在请求系统弹出窗口权限（系统级）...');
      status = await permission.request();
      developer.log('📋 系统弹出窗口权限请求结果: $status');
      
      if (status == PermissionStatus.granted) {
        developer.log('✅ 系统弹出窗口权限请求成功');
        _systemAlertPermissionGranted.value = true;
        return true;
      } else {
        developer.log('❌ 系统弹出窗口权限请求失败: $status');
        _systemAlertPermissionGranted.value = false;
        return false;
      }
      
    } catch (e) {
      developer.log('💥 请求系统弹出窗口权限异常: $e');
      _systemAlertPermissionGranted.value = false;
      return false;
    } finally {
      _isRequestingSystemAlertPermission = false;
      developer.log('🏁 =============== 系统弹出窗口权限请求结束 ===============');
    }
  }

  // 🚀 按顺序申请所有必要权限（强制重新检查通知权限）
  Future<List<String>> requestEssentialPermissionsInOrder({bool forceNotificationRequest = false}) async {
    developer.log('🔐 =============== 开始按顺序申请权限 ===============');
    
    final List<String> grantedPermissions = [];
    
    try {
      // 1. 首先申请通知权限（强制检查以确保弹出系统授权对话框）
      developer.log('📱 步骤1: 申请通知权限${forceNotificationRequest ? "（强制重新申请）" : ""}');
      final notificationGranted = await requestNotificationPermission(forceRequest: forceNotificationRequest);
      if (notificationGranted) {
        grantedPermissions.add('通知权限');
      }
      
      // 等待500ms再申请下一个权限，避免权限申请冲突
      await Future.delayed(const Duration(milliseconds: 500));
      
      // 2. 申请位置权限
      developer.log('📱 步骤2: 申请位置权限');
      final locationGranted = await requestLocationPermission();
      if (locationGranted) {
        grantedPermissions.add('位置权限');
      }
      
      // 等待500ms再申请下一个权限
      await Future.delayed(const Duration(milliseconds: 500));
      
      // 3. 申请麦克风权限
      developer.log('📱 步骤3: 申请麦克风权限');
      final microphoneGranted = await requestMicrophonePermission();
      if (microphoneGranted) {
        grantedPermissions.add('麦克风权限');
      }
      
      // 权限申请结果汇总
      developer.log('🎯 =============== 权限申请结果汇总 ===============');
      developer.log('📱 通知权限: ${_notificationPermissionGranted.value ? "✅ 已授予" : "❌ 未授予"}');
      developer.log('📱 位置权限: ${_locationPermissionGranted.value ? "✅ 已授予" : "❌ 未授予"}');
      developer.log('📱 麦克风权限: ${_microphonePermissionGranted.value ? "✅ 已授予" : "❌ 未授予"}');
      developer.log('🎉 已授予的权限: $grantedPermissions');
      
    } catch (e) {
      developer.log('💥 按顺序权限申请异常: $e');
    } finally {
      developer.log('🏁 =============== 按顺序权限申请结束 ===============');
    }
    
    return grantedPermissions;
  }

  // 🔄 强制重新申请通知权限（用于调试和确认）
  Future<bool> forceRequestNotificationPermission() async {
    developer.log('🔄 =============== 强制重新申请通知权限 ===============');
    return await requestNotificationPermission(forceRequest: true);
  }

  // 🔍 仅检查权限状态（不发送测试通知）
  Future<void> checkPermissionStatus() async {
    developer.log('🔍 =============== 权限状态检查 ===============');
    
    try {
      final notificationStatus = await Permission.notification.status;
      final locationStatus = await Permission.location.status;
      final microphoneStatus = await Permission.microphone.status;
      
      developer.log('📱 当前权限状态:');
      developer.log('🔔 通知权限: $notificationStatus');
      developer.log('📍 位置权限: $locationStatus');
      developer.log('🎤 麦克风权限: $microphoneStatus');
      
    } catch (e) {
      developer.log('💥 权限状态检查异常: $e');
    } finally {
      developer.log('🏁 =============== 权限状态检查结束 ===============');
    }
  }
}